/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.vehicle.modular.vehicleblacklist.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.message.SnowyMessageTemplate;
import vip.xiaonuo.facedoor.modular.message.Topic;
import vip.xiaonuo.facedoor.modular.message.domain.Message;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.vehicle.common.domain.ExcelResult;
import vip.xiaonuo.vehicle.modular.vehicleblacklist.entity.VehicleBlacklist;
import vip.xiaonuo.vehicle.modular.vehicleblacklist.enums.VehicleBlacklistExceptionEnum;
import vip.xiaonuo.vehicle.modular.vehicleblacklist.mapper.VehicleBlacklistMapper;
import vip.xiaonuo.vehicle.modular.vehicleblacklist.param.VehicleBlacklistParam;
import vip.xiaonuo.vehicle.modular.vehicleblacklist.service.VehicleBlacklistService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.vehicle.modular.vehicleinfo.entity.VehicleInfo;
import vip.xiaonuo.vehicle.modular.vehicleinfo.entity.dto.VehicleInfoDto;
import vip.xiaonuo.vehicle.modular.vehicleinfo.param.VehicleInfoParam;
import vip.xiaonuo.vehicle.modular.vehicleinfo.service.VehicleInfoService;
import vip.xiaonuo.vehicle.modular.vehicletrafficrecord.entity.VehicleTrafficRecord;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.LongAdder;

/**
 * 车辆黑名单service接口实现类
 *
 * @author CAD
 * @date 2023-04-11 09:25:44
 */
@Service
public class VehicleBlacklistServiceImpl extends ServiceImpl<VehicleBlacklistMapper, VehicleBlacklist> implements VehicleBlacklistService {
    @Resource
    private VehicleBlacklistMapper vehicleBlacklistMapper;

    @Resource
    private SnowyMessageTemplate snowyMessageTemplate;

    @Override
    public PageResult<VehicleBlacklist> page(VehicleBlacklistParam vehicleBlacklistParam) {
        QueryWrapper<VehicleBlacklist> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(vehicleBlacklistParam)) {

            // 根据车辆型号 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getVehicleModel())) {
                queryWrapper.lambda().eq(VehicleBlacklist::getVehicleModel, vehicleBlacklistParam.getVehicleModel());
            }
            // 根据车辆颜色 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getVehicleColor())) {
                queryWrapper.lambda().eq(VehicleBlacklist::getVehicleColor, vehicleBlacklistParam.getVehicleColor());
            }
            // 根据车牌号码 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getLicensePlateNumber())) {
                queryWrapper.lambda().eq(VehicleBlacklist::getLicensePlateNumber, vehicleBlacklistParam.getLicensePlateNumber());
            }
            // 根据车主姓名 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getCarOwnerName())) {
                queryWrapper.lambda().eq(VehicleBlacklist::getCarOwnerName, vehicleBlacklistParam.getCarOwnerName());
            }
            // 根据联系方式 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getContactWay())) {
                queryWrapper.lambda().eq(VehicleBlacklist::getContactWay, vehicleBlacklistParam.getContactWay());
            }
            // 根据拉黑时间 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getShieldingTime())) {
                String s = vehicleBlacklistParam.getShieldingTime().split(" ")[0];
                queryWrapper.lambda().like(VehicleBlacklist::getShieldingTime, s);
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(vehicleBlacklistParam.getRemark())) {
                queryWrapper.lambda().eq(VehicleBlacklist::getRemark, vehicleBlacklistParam.getRemark());
            }
            queryWrapper.lambda().orderByDesc(VehicleBlacklist::getShieldingTime);
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<VehicleBlacklist> list(VehicleBlacklistParam vehicleBlacklistParam) {
        return this.list();
    }

    @Override
    public void add(VehicleBlacklistParam vehicleBlacklistParam) {
        VehicleBlacklist vehicleBlacklist1 = vehicleBlacklistMapper.selectOne(new LambdaQueryWrapper<VehicleBlacklist>()
                .eq(VehicleBlacklist::getLicensePlateNumber, vehicleBlacklistParam.getLicensePlateNumber()));
        if (ObjectUtils.isNotEmpty(vehicleBlacklist1)) {
            throw new ServiceException(500, "黑名单已存在该车牌！");
        }
        VehicleBlacklist vehicleBlacklist = new VehicleBlacklist();
        BeanUtil.copyProperties(vehicleBlacklistParam, vehicleBlacklist);
        this.save(vehicleBlacklist);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(VehicleBlacklistParam vehicleBlacklistParam) {
        this.removeById(vehicleBlacklistParam.getId());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(VehicleBlacklistParam vehicleBlacklistParam) {
        VehicleBlacklist byId = this.getById(vehicleBlacklistParam.getId());
        if (!byId.getLicensePlateNumber().equals(vehicleBlacklistParam.getLicensePlateNumber())) {
            VehicleBlacklist vehicleInfo1 = vehicleBlacklistMapper.selectOne(new LambdaQueryWrapper<VehicleBlacklist>()
                    .eq(VehicleBlacklist::getLicensePlateNumber, vehicleBlacklistParam.getLicensePlateNumber()));
            if (ObjectUtils.isNotEmpty(vehicleInfo1)) {
                throw new ServiceException(500, "已存在该车牌！");
            }
        }
        VehicleBlacklist vehicleBlacklist = this.queryVehicleBlacklist(vehicleBlacklistParam);
        BeanUtil.copyProperties(vehicleBlacklistParam, vehicleBlacklist);
        this.updateById(vehicleBlacklist);
    }

    @Override
    public VehicleBlacklist detail(VehicleBlacklistParam vehicleBlacklistParam) {
        return this.queryVehicleBlacklist(vehicleBlacklistParam);
    }

    @Override
    public void export(VehicleBlacklistParam vehicleBlacklistParam) {
        List<VehicleBlacklist> list = this.list(vehicleBlacklistParam);
        PoiUtil.exportExcelWithStream("车辆黑名单.xls", VehicleBlacklist.class, list);
    }

    @Override
    public ResponseData importData(MultipartFile file) {
        List<VehicleBlacklist> vehicleBlacklists = PoiUtil.importExcel(file, 0, 1, VehicleBlacklist.class);
        if (CollectionUtils.isEmpty(vehicleBlacklists)) {
            throw new ServiceException(500, "没有有效的数据！");
        }
        LongAdder successLongAdder = new LongAdder();
        LongAdder failLongAdder = new LongAdder();
        ExcelResult excelResult = new ExcelResult();
        List<ExcelResult.FailMessage> failMessageList = new ArrayList<>();
        for (VehicleBlacklist vehicleBlacklist : vehicleBlacklists) {
            ExcelResult.FailMessage failMessage = new ExcelResult.FailMessage()
                    .setFlag("车牌号").setName(Optional.of(vehicleBlacklist.getLicensePlateNumber()).orElse("标识字段为空"));
            checkAndSave(vehicleBlacklist, successLongAdder, failLongAdder, failMessage);
            failMessageList.add(failMessage);
        }
        excelResult.setSuccessNum(successLongAdder.intValue())
                .setFailNum(failLongAdder.intValue())
                .setFailMessageList(failMessageList);
        return ResponseData.success(excelResult);
    }

    private void checkAndSave(VehicleBlacklist vehicleBlacklist, LongAdder successLongAdder, LongAdder failLongAdder, ExcelResult.FailMessage failMessage) {
        if (StringUtils.isEmpty(vehicleBlacklist.getLicensePlateNumber())) {
            failMessage.setFailMessage("车牌号不能为空！");
            failLongAdder.increment();
            return;
        }
        if (StringUtils.isEmpty(vehicleBlacklist.getCarOwnerName())) {
            failMessage.setFailMessage("车主姓名不能为空！");
            failLongAdder.increment();
            return;
        }
        VehicleBlacklist vehicleInfo1 = vehicleBlacklistMapper.selectOne(new LambdaQueryWrapper<VehicleBlacklist>()
                .eq(VehicleBlacklist::getLicensePlateNumber, vehicleBlacklist.getLicensePlateNumber()));
        if (ObjectUtils.isNotEmpty(vehicleInfo1)) {
            throw new ServiceException(500, "已存在该车牌！");
        }
        if (StringUtils.isEmpty(vehicleBlacklist.getContactWay())) {
            failMessage.setFailMessage("联系方式不能为空！");
            failLongAdder.increment();
            return;
        }
        if (null == vehicleBlacklist.getShieldingTime()) {
            failMessage.setFailMessage("拉黑时间不能为空！");
            failLongAdder.increment();
            return;
        }
        saveBean(vehicleBlacklist, successLongAdder, failLongAdder, failMessage);
    }

    private void saveBean(VehicleBlacklist vehicleBlacklist, LongAdder successLongAdder, LongAdder failLongAdder, ExcelResult.FailMessage failMessage) {
        VehicleBlacklistParam vehicleBlacklistParam = new VehicleBlacklistParam();
        BeanUtils.copyProperties(vehicleBlacklist, vehicleBlacklistParam);
        try {
            this.add(vehicleBlacklistParam);
            successLongAdder.increment();
        } catch (Exception e) {
            failLongAdder.increment();
            failMessage.setFailMessage(e.getMessage());
        }
    }

    /**
     * 获取车辆黑名单
     *
     * @author CAD
     * @date 2023-04-11 09:25:44
     */
    private VehicleBlacklist queryVehicleBlacklist(VehicleBlacklistParam vehicleBlacklistParam) {
        VehicleBlacklist vehicleBlacklist = this.getById(vehicleBlacklistParam.getId());
        if (ObjectUtil.isNull(vehicleBlacklist)) {
            throw new ServiceException(VehicleBlacklistExceptionEnum.NOT_EXIST);
        }
        return vehicleBlacklist;
    }
}
